import smtplib
from email.mime.image import MIMEImage
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

HOST = "smtp.qq.com"
SUBJECT = "业务性能数据报表"
TO = "15606711836@163.com"
FROM = "820850938@QQ.COM"
USER = "820850938@QQ.COM"
PASSWD = "iabwkcwgyrkpbdfb"

# 定义添加图片函数
def add_img(src, imgid):                #  添加图片 图片路径 和id
    with open(src, 'rb') as f:
        msgImage = MIMEImage(f.read())  # MIMEImage 对象 图片内容为参数

    msgImage.add_header('Content-ID', imgid)  # 指定 图片的content-id
    return msgImage

msg = MIMEMultipart('related')           ##采用related定义内嵌资源的邮件体

msgtext = MIMEText("""
            <table width="800" border="0" cellspace="0" cellpadding="4">
                 <tr>
                 <td bgcolor="#CECFAD" height="20" style="font-size: 14px">*官网数据 <ahref="http://monitor.domain.com/">更多>></a></td>
                  </tr>
                  <tr bgcolor="#CEFFAD" height="100" style="font-size: 13px">
				  <td>
				  <img src="cid:io"></td>
				  <td>
				  <img src="cid:key_hit">
				  </td>
				  </tr>
				  <tr bgcolor="#EEFCAD" height="100" style="font-size: 13px">
				  <td>
				  <img src="cid:men"></td>
				  <td>
				  <img src="cid:swap"></td>
				  </tr>
				  </table>""", "html", "utf-8")

msg.attach(msgtext)                                         # MIMEMultipart 对象附加 MIMEText 对象实例的内容
msg.attach(add_img("img/bytes_io.png", "io"))               # MIMEMultipart 对象附加 MIMEImage 的内容
msg.attach(add_img("img/myisam_key_hit.png", "key_hit"))
msg.attach(add_img("img/os_mem.png", "men"))
msg.attach(add_img("img/os_swap.png", "swap"))

msg['SUBJECT'] = SUBJECT
msg['TO'] = TO
msg['FROM'] = FROM

try:
    server = smtplib.SMTP()
    server.connect(HOST, port=25)
    server.starttls()
    server.login(USER, PASSWD)
    server.sendmail(FROM, [TO], msg.as_string())
    server.quit()
    print("邮件发送成功")
except Exception:
    print("邮件发送失败")


